package com.tencent.filter;

import com.alibaba.fastjson.JSONObject;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;

@Component
public class LoginFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        // 获取请求地址
        String url = RequestContext.getCurrentContext().getRequest().getRequestURI();
        if (url.endsWith("login") || url.endsWith("register")){
            return false;
        }
        return true;
    }

    @Override
    public Object run() throws ZuulException{
        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();
        HttpServletResponse response = RequestContext.getCurrentContext().getResponse();

        response.setContentType("application/json;charset=utf-8");

        String token = request.getHeader("token");
        // 判断token是否为空
        if (StringUtils.isEmpty(token)){
            try {
                PrintWriter writer = response.getWriter();
                HashMap<String, Object> map = new HashMap<>();
                map.put("success", false);
                map.put("message", "没有登录哦");
                map.put("obj", "noLogin");
                String jsonMap = JSONObject.toJSONString(map);
                writer.write(jsonMap);
                RequestContext.getCurrentContext().setSendZuulResponse(false);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return null;
    }
}
